#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#define BUFF_SIZE 256

int main(int argc, char ** argv) {
	if (argc != 4) {
		perror("Wrong number of parameters.\nUsage: ./client <ip_address> <port_number> <file_path>");
		return -1;
	}
	
	struct sockaddr_in server_address;
	int socket_fd, len, file_fd;
	socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (socket_fd < 0) {
		perror("Socket opening");
		return -2;
	}
	
	bzero((char *)&server_address, sizeof(server_address));
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = inet_addr(argv[1]);
	server_address.sin_port = htons(atoi(argv[2]));
	
	printf("Opening file: %s\n", argv[3]);
	file_fd = open(argv[3], 0, O_RDONLY);
	if (file_fd < 0) {
		perror("open file");
		close(socket_fd);
		return -3;
	}
	
	printf("Connecting to socket on port: %s\n", argv[2]);
	if (connect(socket_fd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
		perror("Connect");
		close(socket_fd);
		close(file_fd);
		return -4;
	}
	
	int length;
	char buffer[BUFF_SIZE];
	while ((length = read(file_fd, &buffer, BUFF_SIZE)) > 0) {
		if (send(socket_fd, &buffer, length, 0) != length) {
			perror("Buffer send");
			close(socket_fd);
			close(file_fd);
			exit(-1);
		}
	}
	printf("Closing socket and file\n");	
	close(socket_fd);
	close(file_fd);
	return 0;	
}
